import { DeterminedPlan, RelevantPlan } from "../class/structure/structure";
import { errLog } from "../util/log";

/**
 * 
 * @param {DeterminedPlan} plan 
 * @returns {CreepActionReturnCode}
 */
export function planStructure(...plans){
    return addPlan(...plans);
}

export const globalStructure = {
    init(){
        this.plans = [];
    },
    restoreStructures(){
        let memory = Memory.plans;
        if(!memory || typeof memory !== 'object'){
            Game.plans = {};
            return;
        }
        let plans = {};
        for(let name in memory){
            let mem = memory[name];
            if(!mem){
                continue;
            }
            try{
                let plan;
                if(mem.determined){
                    plan = new DeterminedPlan().deserialize(mem.obj);
                }else{
                    plan = new RelevantPlan().deserialize(mem.obj);
                }
                plans[name] = plan;
            }catch(e){
                errLog(e);
            }
        }
        Game.plans = plans;
    },
    saveStructures(){

        let memory = {};
        let plans = Game.plans;

        if(!plans || typeof plans !== 'object'){
            Memory.plans = {};
            return;
        }
        for(let name in plans){
            let plan = plans[name];
            if(!plan){
                continue;
            }
            try{
                let mem = {
                    obj: plan.serialize(),
                    determined: (plan instanceof DeterminedPlan),
                };
                memory[name] = mem;
            }catch(e){
                errLog(e);
            }
        }
        Memory.plans = memory;
    },
    run(){
        if(!(this.plans instanceof Array)){
            return;
        }
        for(let plan of this.plans){
            if(!(plan instanceof DeterminedPlan)){
                continue;
            }
            if(!plan.isDone()){
                plan.buildAll();
            }
        }
    },
    addPlan(...plans){
        if(!(this.plans instanceof Array)){
            this.plans = [];
        }
        this.plans.push(...plans);
    }
}